<template>
  <!-- 文件平铺 -->
  <div class="file_grid_wrapper">
    <ul class="file_list" v-loading="loading" element-loading-text="文件加载中...">

      <li class="file_item"
          v-for="(item,index) in dataList"
          :key="index"
          :class="item.checked?'checked':''"
          @contextmenu.prevent="handleContextMenu($event,index)"
          @click="ClickItem(item,index)"
          @dblclick="fileClick(item)"

      >
        <div>
          <div v-if="item.fileType==3" class="videoContent">
            <img class="video_img" src="@/assets/images/video_img.png" alt="加载失败">
            <video-review class="video_box" :ref="`videoReview-${index}`" :videoSrc="item.url"></video-review>
          </div>
          <div style="width: 60px;height: 60px;margin: auto" v-else>
            <img src="@/assets/image_library/dirlarge.png" v-if="item.isDir==1" :style="`height:60px; width:60px;`"/>
            <el-image
              class="file-img"
              :src="item.url"
              :style="`height:60px; width:60px;`"
              fit="cover"
              v-else-if="item.fileType==4"
            />
            <el-image
              class="file-img"
              :src="FileImage[item.extendName]? FileImage[item.extendName]:require('@/assets/image_library/neticon.png')"
              :style="`height:50px; width:50px`"
              fit="cover"
              v-if="item.fileType!=4&&item.fileType!=3&&item.isDir!=1"
            />
          </div>

        </div>
        <el-tooltip class="item" effect="dark" :content="item.keyName" placement="top-end" v-if="item.isDir">
          <div
            class="file-name"
          >{{ item.keyName }}
          </div>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="item.keyName+'.'+item.extendName" placement="top-end" v-if="!item.isDir">
          <div
            class="file-name"
          >{{ item.keyName }}.{{ item.extendName }}
          </div>
        </el-tooltip>

        <div
          :class="item.checked?'file-checked-wrapper checked':'file-checked-wrapper'"
        >
          <div class="item_top">
            <div @click.stop>
              <el-checkbox
                class="file-checked"
                v-model="item.checked"
                @change="checkChange"
              />
            </div>
            <div @click.stop>
              <el-dropdown trigger="click" placement="bottom-start" @command="handleCommand" :ref="`moreBtns_${index}`">
               <span class="moreBtns">
                 <i class="el-icon-more"></i>
               </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{...item,type:'open',index:index}">
                    <i class="el-icon-zoom-in"></i>
                    打开
                  </el-dropdown-item>
                  <el-dropdown-item :command="{...item,type:'downLoad'}" v-if="item.isDir!=1">
                    <i class="el-icon-download"></i>
                    下载
                  </el-dropdown-item>
                  <el-dropdown-item :command="{...item,type:'copy'}">
                    <i class="el-icon-document-copy"></i>
                    复制到
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </div>
      </li>
    </ul>
    <copyFormCourse ref="copyFormCourse" @uploadNew="uploadNewFile"></copyFormCourse>
    <fileDrawer
      :show.sync="drawer"
      :url="drawerurl"
      :name="drawername"
      :type="drawertype"
    ></fileDrawer>
  </div>
</template>

<script>
import videoReview from '@/components/videoReview/videoReview.vue'
import copyFormCourse from '@/views/library_homePage/component/copyFormCourse.vue'
import DetailMsg from '@/views/library_homePage/component/DetailMsg.vue'
import AudioDialog from '@/views/library_homePage/component/audioDialog.vue'
import { mapGetters, mapMutations } from 'vuex'
import fileDrawer from '@/components/fileDrawer.vue'
import { savedownloadFile } from '@/api/library_filrList/fileList'
import { saveAs } from 'file-saver'

export default {
  name: 'courseList',
  components: { AudioDialog, DetailMsg, copyFormCourse, videoReview, fileDrawer },
  model: {
    prop: 'value',
    event: 'update:value'
  },
  props: {
    fileList: Array,//  文件列表
    value: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    fileList: {
      handler(val) {
        if (val && Array.isArray(val) && val.length > 0) {
          let arr = JSON.parse(JSON.stringify(val))
          this.dataList = arr.map(item => {
            return {
              ...item,
              checked: false
            }
          })
        }
      },
      deep: true,
      immediate: true
    },
    value: {
      handler(val) {
        this.checkAllChange(val)
      }
    }
  },
  data() {
    return {
      loading: false,
      dataList: [],
      drawer: false,
      drawerurl: '',
      drawername: '',
      drawertype: '',
      FileImage: {
        'pdf': require('@/assets/image_library/pdficon.png'),
        'docx': require('@/assets/image_library/wordIcon.png'),
        'dov': require('@/assets/image_library/wordIcon.png'),
        'xls': require('@/assets/image_library/excelicon.png'),
        'xlsx': require('@/assets/image_library/excelicon.png'),
        'ppt': require('@/assets/image_library/ppticon.png'),
        'pptx': require('@/assets/image_library/ppticon.png'),
        'txt': require('@/assets/image_library/texticon.png'),
        'zip': require('@/assets/image_library/zipicon.png'),
        'rar': require('@/assets/image_library/zipicon.png'),
        'mp3': require('@/assets/image_library/musicicon.png')
      },
      clickTimeout: null
    }
  },
  computed: {
    ...mapGetters('libraryFile', ['pathArr', 'courseArr']),
    isCheckAll() {
      return this.dataList.filter(item => item.checked).length === this.dataList.length
    }
  },
  methods: {
    ...mapMutations('libraryFile', ['removecoursePath', 'clearcoursePathArr', 'addcoursePath']),
    handleContextMenu(event, index) {
      event.preventDefault()
      setTimeout(() => {
        this.$refs[`moreBtns_${index}`][0].show()
      }, 300)
    },
    ClickItem(item, index) {
      // 清除之前的定时器
      clearTimeout(this.clickTimeout)

      // 设置一个新的定时器来延迟单击事件的触发
      this.clickTimeout = setTimeout(() => {
        this.dataList[index].checked = !this.dataList[index].checked
        this.checkChange()
        // 在这里处理单击事件
      }, 200) // 200ms 的延迟时间

    },
    /**
     * 文件点击事件
     * @param item
     */
    fileClick(item) {
      clearTimeout(this.clickTimeout)
      if (item.isDir === 1) {
        this.$emit('nextCourse', { keyType: item.keyType, keyId: item.keyId, indexType: item.indexType, folderNo: item.folderNo })
        this.addcoursePath(item)
        // 如果是文件夹则进入下一级
      } else {
        this.lookFiles(item.url, item.keyName)
      }
    },
    lookFiles(url, name) {
      let uploadType = url.slice(url.lastIndexOf('.'), url.length).toLowerCase()
      let arr = [
        '.gif',
        '.png',
        '.jpeg',
        '.jpg',
        '.mp4',
        '.webm',
        '.pdf',
        '.wps',
        '.docx',
        '.doc',
        '.rtf',
        '.pptx',
        '.ppt',
        '.xls',
        '.xlsx',
        '.wps',
        '.ofd',
        '.txt',
        '.js',
        '.json',
        '.css',
        '.sql',
        '.xml',
        '.java',
        '.cs(c#)'
      ]
      if (arr.indexOf(uploadType) > -1) {
        this.drawer = true
        this.drawerurl = url
        this.drawername = name
        this.drawertype = 1
      } else if (uploadType == '.mp3') {
        window.open(url, '_blank')
      } else {
        this.$message.info('暂不支持在线预览，请下载后查看')
      }
    },
    checkChange() {
      this.$emit('checklist', { arr: this.dataList.filter(item => item.checked) })
      if (this.isCheckAll) {
        this.$emit('update:value', true)

      } else if (this.dataList.filter(item => item.checked).length === 0) {
        this.$emit('update:value', false)
      }
    },
    // 全选
    checkAllChange(val) {
      this.dataList.forEach(item => {
        item.checked = val
      })
      this.$emit('checklist', { arr: this.dataList.filter(item => item.checked) })
    },
    handleCommand(command) {
      switch (command.type) {
        case 'copy':
          this.$refs.copyFormCourse.show([command])
          break
        case 'open':
          this.fileClick(command)
          break
        case 'downLoad':
          saveAs(command.url, command.keyName)
          // 调取下载记录接口
          // TODO:单独记录下载
          if (this.map == 'group') {
            this.saveDownload(command.fileName, command.extendName, command.filePath, command.id, command.fileSize, this.groupId)
          } else {
            this.saveDownload(command.fileName, command.extendName, command.filePath, command.id, command.fileSize)
          }
          break
      }
    },
    // 刷新
    uploadNewFile(data) {
      this.$parent.getCourseList(data.keyId, data.keyType, data.indexType)
    },
    // 记录下载文件
    async saveDownload(fileName, extendName, filePath, fileId, fileSize, groupId) {
      let obj = {
        fileName,
        extendName,
        filePath,
        groupId: groupId || '',
        fileId,
        fileSize
      }
      await savedownloadFile(obj)
    }
  }
}

</script>


<style scoped lang="scss">
.file_grid_wrapper {
  padding: 10px;
  box-sizing: border-box;
  height: 100%;

  .file_list {
    height: 100%;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    align-content: flex-start;
    list-style: none;

    .file_item {
      width: 130px;
      height: 120px;
      margin: 0 16px 16px 0;
      position: relative;
      padding: 25px 16px 8px 16px;
      box-sizing: border-box;
      text-align: center;
      cursor: pointer;
      z-index: 1;
      border-radius: 10px;

      .videoContent {
        position: relative;
        height: 60px;
        width: 60px;
        left: 50%;
        transform: translateX(-50%);

        .video_img {
          width: 24px;
          height: 24px;
          object-fit: cover;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }

        .video_box {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #f5f5f5;
          border-radius: 8px;
          cursor: pointer;

        }
      }

      &:hover {
        background: rgba(245, 247, 250, 0.5);

        .file-checked-wrapper {
          position: absolute;
          z-index: -1;
          display: block;
        }
      }

      .file-name {
        margin-top: 8px;
        height: 24px;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .file-checked-wrapper {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        width: 100%;
        height: 100%;
        display: none;

        .item_top {
          display: flex;
          position: absolute;
          top: 10px;
          left: 0;
          padding: 0 10px;
          box-sizing: border-box;
          width: 100%;
          align-items: center;
          justify-content: space-between;

          .file-checked {
          }

          .moreBtns {
            display: inline-block;
            height: 19px;
            line-height: 19px;
          }
        }

      }

      .file-checked-wrapper.checked {
        display: block;
      }
    }

    .file_item.checked {
      background-color: #e3f3ee;
    }
  }
}
</style>
